package com.ll.wechat.chatRecord.fragment;

import java.util.ArrayList;
import java.util.Collection;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.ll.wechat.R;
import com.ll.wechat.base.app.Constant;
import com.ll.wechat.base.fragment.BaseFragment;
import com.ll.wechat.base.utils.thread.ThreadPoolUtil;
import com.ll.wechat.chat.activity.ChatActivity;
import com.ll.wechat.chatRecord.adapter.ChatRecordListAdapter;
import com.ll.wechat.chatRecord.bean.ChatRecord;
import com.ll.wechat.database.DataBaseHelperUtil;

/**
 * 微信tab第一项列表
 * 
 * @ClassName: ChatListFragment
 * @author yeliangliang
 * @date 2015-8-4 下午3:15:11
 */
public class ChatListFragment extends BaseFragment implements OnItemClickListener {

	private ListView mListView;// 聊天记录列表
	private ChatRecordListAdapter mAdapter;
	private ArrayList<ChatRecord> mList;
	private MessageBroadCastReceiver mReceiver;// 消息接收器
	private DataBaseHelperUtil util;
	private final static int DATA_SUCCESS = 10000;// 数据查询成功标识

	@Override
	public int setRootViewId() {
		return R.layout.fragment_chat_record_list;
	}

	@Override
	protected void initView(View rootView) {
		mListView = (ListView) rootView.findViewById(R.id.listView_chat_record);
		mListView.setOnItemClickListener(this);
		mList = new ArrayList<ChatRecord>();
		mAdapter = new ChatRecordListAdapter(getActivity(), mList);
		mListView.setAdapter(mAdapter);
	}

	@Override
	protected void initData() {
	}

	/**
	 * 消息接收广播 接收来自服务器的消息提醒
	 * 
	 * @ClassName: MessageBroadCastReceiver
	 * @author yeliangliang
	 * @date 2015-8-4 上午11:57:37
	 */
	private class MessageBroadCastReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			String from = "";
			String content = "";
			int code = 1 ;
			try {
				from = intent.getExtras().getString("from");
				content = intent.getExtras().getString("body");
				code = mReceiver.getResultCode();
			} catch (Exception e) {
				Log.e("ChatListFragment", "删除好友");
			}
			if (code == 0) {// 已读信息
				/**
				 * 信息在聊天界面已被存储
				 */
			} else {// 未读信息
				// 存储聊天信息
				saveChatRecord(from, content);
			}

		}
	}

	/**
	 * 存储接收到的消息
	 * 
	 * @param from
	 * @param content
	 * @author yeliangliang
	 * @date 2015-8-6 下午4:32:42
	 * @version V1.0
	 * @return void
	 */
	private void saveChatRecord(final String from, final String content) {
		Runnable runnable = new Runnable() {

			@Override
			public void run() {
				if (content.equals("")|| from .equals("")) {
					handler.obtainMessage(DATA_SUCCESS, util.searchNewRecord()).sendToTarget();
					return;
				}
				ChatRecord chatRecord = new ChatRecord();
				chatRecord.setContent(content);
				chatRecord.setName(from.split("@")[0]);
				chatRecord.setPassName(from);
				chatRecord.setSource("you");
				chatRecord.setTime(System.currentTimeMillis() + "");
				chatRecord.setStaues("1");
				util.insertNewRecord(chatRecord);
				util.insertToTable(DataBaseHelperUtil.TABLE_NAME_CHAT_RECORD, chatRecord);
				// 查询数据并展示
				handler.obtainMessage(DATA_SUCCESS, util.searchNewRecord()).sendToTarget();
			}
		};
		ThreadPoolUtil.insertTaskToCatchPool(runnable);
	}

	@Override
	public void onResume() {
		super.onResume();
		// 注册广播
		if (mReceiver == null) {
			mReceiver = new MessageBroadCastReceiver();
		}
		util = DataBaseHelperUtil.getInstance(getActivity());
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.setPriority(800);
		intentFilter.addAction(Constant.RECIVER_MESSAGE);
		getActivity().registerReceiver(mReceiver, intentFilter);
		// 查询数据并展示
		searchDataAndDisplay();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		// 注销广播 关闭数据库
		if (mReceiver != null) {
			getActivity().unregisterReceiver(mReceiver);
		}
	}

	/**
	 * 跨线程操作
	 */
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case DATA_SUCCESS:
				mList.clear();
				mList.addAll((Collection<? extends ChatRecord>) msg.obj);
				mAdapter.notifyDataSetChanged();
				break;

			default:
				break;
			}
		}

	};

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		Bundle bundle = new Bundle();
		bundle.putString("name", mList.get(position).getName());
		bundle.putString("passName", mList.get(position).getPassName());
		showActivity(getActivity(), ChatActivity.class, bundle);
	}

	/**
	 * 查询数据并展示
	 * 
	 * @author yeliangliang
	 * @date 2015-8-7 上午11:23:10
	 * @version V1.0
	 * @return void
	 */
	private void searchDataAndDisplay() {
		// 查询数据并展示
		Runnable runnable = new Runnable() {

			@Override
			public void run() {
				handler.obtainMessage(DATA_SUCCESS, util.searchNewRecord()).sendToTarget();
			}
		};
		ThreadPoolUtil.insertTaskToCatchPool(runnable);
	}
}
